﻿using com.kmer.interfaces;
using com.kmer.library.Factorys;
using kmer.Web.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;

// ReSharper disable once CheckNamespace
namespace com.kmer.Helper
{
    /// <summary>
    /// 和图片相关的操作类
    /// </summary>
    public static class ImageHelper {
		/// <summary>
		/// 返回完整的图片地址
		/// </summary>
		/// <param name="page"></param>
		/// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
		/// <param name="protocol">协议</param>
		/// <returns></returns>
		public static string GetImageUrl(this Page page, string url, string protocol = "http") {
			//if (url.StartsWith("~/"))
			url = page.Request.ResolveClientUrl(url);
			return GetImageUrl(url, protocol);
		}
		/// <summary>
		/// 返回完整的图片地址
		/// </summary>
		/// <param name="request"></param>
		/// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
		/// <param name="protocol">协议</param>
		/// <returns></returns>
		public static string GetImageUrl(this HttpRequest request, string url, string protocol = "http") {
			//if (url.StartsWith("~/"))
			url = request.ResolveClientUrl(url);
			return GetImageUrl(url, protocol);
		}
		///// <summary>
		///// 返回完整的图片地址
		///// </summary>
		///// <param name="httpHandler"></param>
		///// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
		///// <param name="protocol">协议</param>
		///// <returns></returns>
		//public static string GetImageUrl(this IHttpHandler httpHandler, string url, string protocol = "http") {
		//          return GetImageUrl(url, protocol);
		//}
		/// <summary>
		///  返回完整的图片地址
		/// </summary>
		/// <param name="context"></param>
		/// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
		/// <param name="protocol">协议</param>
		/// <returns></returns>
		public static string GetImageUrl(this interfaces.ISessionContext context, string url, string protocol = "http") {
			//if (url.StartsWith("~/"))
			url = context.Request.ResolveClientUrl(url);
			return GetImageUrl(url, protocol);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="url"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="isCut"></param>
		/// <param name="protocol"></param>
		/// <returns></returns>
		public static string GetImageUrl(this interfaces.ISessionContext context, string url, int width, int height, bool isCut = false, string protocol = "http") {
			//if (url.StartsWith("~/"))
			url = context.Request.ResolveClientUrl(url);
			return GetImageUrl(url, width, height, isCut, protocol);
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="url"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="isCut"></param>
		/// <param name="protocol"></param>
		/// <returns></returns>
		public static string GetImageUrl(string url, int width, int height, bool isCut = false, string protocol = "http") {
			if (string.IsNullOrWhiteSpace(url)) return url;
			if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) {
				return url.Replace("/~/", "/");
			}

			if (HttpContext.Current != null) {
				url = HttpContext.Current.Request.ResolveClientUrl(url);
			}
			var r = new UriBuilder() {
				Scheme = protocol,
				Host = ConfigurationHelper.Get("image-host", "img.kmer.com"),
				//Port = 80,
				Path = url
			};
			var style = "";
			if (width > 0) {
				style += $"_{width}w";
			}
			if (height > 0) {
				style += $"_{height}h";
			}
			if (isCut) {
				style += $"_cut";
			}
			if (!string.IsNullOrWhiteSpace(style)) {
				r.Query = "?" + style;
			}
			var port = ConfigurationHelper.Get("image-host-port", 80);
			if (port != 80)
				r.Port = port;
			return r.ToString();
		}


        /// <summary>
        /// 返回完整的图片地址
        /// </summary>
        /// <param name="url">图片地址，如果已经是完整的Uri（带“http://"）则直接返回</param>
        /// <param name="protocol">协议</param>
        /// <returns></returns>
        public static string GetImageUrl(string url, string protocol = "http") {
			if (string.IsNullOrWhiteSpace(url)) return url;
			if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) {
				return url.Replace("/~/", "/");
			}
			if (HttpContext.Current != null) {
				url = HttpContext.Current.Request.ResolveClientUrl(url);
			}
			var r = new UriBuilder() {
				Scheme = protocol,
				Host = ConfigurationHelper.Get("image-host", "img.kmer.com"),
				//Port = 80,
				Path = url
			};
			var port = ConfigurationHelper.Get("image-host-port", 80);
			if (port != 80)
				r.Port = port;
			return r.ToString();
		}
		/// <summary>
		/// 删除图片
		/// </summary>
		/// <param name="imgs"></param>
		public static void RemoveImages(IEnumerable<string> imgs) {
			var context = HttpContext.Current;
			foreach (var img in imgs) {
				var file = "";
				try {
					file = context.Server.MapPath(img);
				} catch {
					continue;
				}
				var fileInfo = new FileInfo(file);
				if (!fileInfo.Exists) continue;
				//如果路径中不包含“upfile”则为非法操作
				if (!fileInfo.FullName.ToLower().Contains("/upfile/")) return;
				try {
					fileInfo.Delete();
				} catch (Exception ex) {
					Log.Error(ex, "Remove Image " + img);
				}
			}
		}
		public static void RemoveImages(IEnumerable<ImageItem> imgs) {
			var context = HttpContext.Current;
			foreach (var img in imgs) {
				if (string.IsNullOrWhiteSpace(img.BucketName)) {
					var file = "";
					try {
						file = context.Server.MapPath(img.Url);
					} catch {
						continue;
					}
					var fileInfo = new FileInfo(file);
					if (!fileInfo.Exists) continue;
					//如果路径中不包含“upfile”则为非法操作
					if (!fileInfo.FullName.ToLower().Contains("/upfile/")) return;
					try {
						fileInfo.Delete();
					} catch (Exception ex) {
						Log.Error(ex, "Remove Image " + img);
					}
				} else{
					var factory = FactoryMaker.Get<IOssClient>("OSS-Factory", "AlOss.OssClientFactory,AlOss");
					factory.RemoveObject(img.BucketName, img.Url);
				}
			}
		}

        /// <summary>
        /// 流水号(订货会审版系统)
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetOSSImageUrl(this HttpRequest request, string key, string OrderName, int source)
        {
            var variable = string.Empty;
            if (source == (int)ImageSource.order)
                variable = "order/"+ OrderName + "/";
            if (source == (int)ImageSource.goods)
                variable = "km/small/";
            return $"http://online-pic.oss-cn-shenzhen.aliyuncs.com/{variable}{key}.jpg";
        }

        /// <summary>
        /// 获取待审商品列表V2 api 中的图片地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="MasterID">订货会ID</param>
        /// <param name="SerialNo">流水号</param>
        /// <returns></returns>
        public static string GetOSSImageUrlV2(this HttpRequest request, int MasterID, string SerialNo)
        {
            return $"http://kmer-online-pic.oss-cn-shenzhen.aliyuncs.com/OrderApp/{MasterID}/{SerialNo}.jpg";
        }

        public class ImageItem {
			public string Url { get; set; }
			public string BucketName { get; set; }

			public ImageItem() {
			}

         
        }

        /// <summary>
        /// 从oss获取图片
        /// </summary>
        public enum ImageSource
        {
            /// <summary>
            /// 订货会图片
            /// </summary>
            order=1,
            /// <summary>
            /// 商品提供图片
            /// </summary>
            goods=2
        }
    }

  
}
